package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */

@Slf4j

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @RestControllerAdvice // advice通知、建议 切面aop技术
    public class GlobalExceptionHandler {

        @ExceptionHandler(value= SQLIntegrityConstraintViolationException.class) // try catch中的catch作用，是用来捕获指定类型的异常
        // 返回值与方法名自定义
        // 参数 必须是捕获的异常
        //public String abc(SQLIntegrityConstraintViolationException e){
        public Result abc(SQLIntegrityConstraintViolationException e){
            // Caused by: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '钓鱼佬' for key 'dept.name'
            // Duplicate entry '钓鱼佬' for key 'dept.name'
            String message = e.getMessage();
            // 返回提示：操作失败，xxx 已存在
            //return message;
            String[] strings = message.split(" ");
            String msg = strings[2];
            //return "操作失败," + msg +  " 已存在!";
            return Result.error("操作失败," + MessageConstant.AlREADY_EXISTS);
        }

    /**
     * 业务异常处理
     * @param e
     * @return
     */
        @ExceptionHandler(BaseException.class)
        public Result<String> handleBaseException(BaseException e){
            return Result.success(e.getMessage());
        }
}
